#include "RS232.h"
#include "../ACUAS/ACUAS.h"

#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include "../ACUAS/UART/uart.h"

#define UART_BAUD_RATE 1200

void
rs232_initialize()
{
  uart_init(UART_BAUD_SELECT(UART_BAUD_RATE, F_CPU));
  sei();
}

void
rs232_card_dealt(Card card)
{
  uart_putc('C');
  uart_putc(card);
}

void
rs232_shuffling()
{
  uart_putc('S');
}

unsigned char
rs232_hit_or_stand(Hand *player, unsigned char send)
{
  if (send) {
    uart_putc('H');
    uart_putc(hand_get_score(player));
  }

  delay_ds(1);

  unsigned char response = uart_getc();
  if (response != 'H')
    return 0;

  response = uart_getc();
  if (response == 'h')
    return 2;
  else if (response == 's')
    return 1;
  else
    return 0;
}

unsigned int
rs232_get_bet(unsigned int maximum, unsigned char send)
{
  if (send) {
    uart_putc('B');
    uart_putc(maximum >> 8);
    uart_putc(maximum);
  }

  delay_ds(1);

  unsigned char response = uart_getc();
  if (response != 'B')
    return 0;

  delay_ds(1);

  unsigned int value = (uart_getc() << 8) + uart_getc();
  if (value <= 0 || value > maximum)
    return 0;

  return value;
}

unsigned char
rs232_skip_screen(unsigned char send)
{
  if (send)
    uart_putc('X');

  delay_ds(1);

  return (uart_getc() == 'X') ? 1 : 0;
}
